<template>
  <div class="component-manage-level-vip distribution-level-set bottom-redius">
    <div class="main-container">
      <div class="operation-bar">
        <div
          v-if="isAuth('user:userLevel:save')"
          class="default-btn primary-btn"
          @click="onAddRow"
        >
          {{ $t('user.addLevel') }}
        </div>
      </div>
      <div class="table-con">
        <el-table
          :data="dataForm.userLevels"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          style="width: 100%"
        >
          <el-table-column
            prop="level"
            fixed
            :label="$t('user.level')"
            width="100"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.level }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="levelName"
            fixed
            :label="$t('user.levelName')"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.levelName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="img"
            fixed
            :label="$t('user.bgImg')"
          >
            <template #default="scope">
              <div class="table-cell-image">
                <img
                  v-if="scope.row.img"
                  :src="checkFileUrl(scope.row.img)"
                  width="140"
                  height="60"
                  @error="scope.row.img=''"
                >
                <span v-if="!scope.row.img">{{ $t('prodList.noPictures') }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="presScore"
            fixed
            :label="$t('user.bonusPoints')"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.presScore }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="needAmount"
            :label="$t('user.paidMemberPrice')"
            min-width="100px"
          >
            <template #default="scope">
              <span>{{ scope.row.needAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="termType"
            :label="$t('user.time')"
            min-width="100px"
          >
            <template #default="scope">
              <span>{{ scope.row.termType === 1? $t('coupon.day') :scope.row.termType === 2? $t('user.week') :scope.row.termType === 3? $t('user.month') :scope.row.termType === 4? $t('user.season') : $t('user.year') }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="needGrowth"
            :label="$t('user.needGrowth')"
          >
            <template #default="scope">
              <span>{{ scope.row.needGrowth }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="discountRange"
            fixed
            :label="$t('user.memberDiscount')"
          >
            <template #default="scope">
              <span v-if="scope.row.discount==10">{{ $t('chat.none') }}</span>
              <span v-else>
                {{ scope.row.term }}
                {{ scope.row.termType === 1? $t('coupon.day') :scope.row.termType === 2? $t('user.week') :scope.row.termType === 3? $t('user.month') :scope.row.termType === 4? $t('user.season') : $t('user.year') }}{{ $t('user.within') }}
                {{ scope.row.discountRange === 1? $t('user.selfShop') : $t('user.platform') }}
                {{ scope.row.discountType === 1? $t('user.someProducts') : $t('user.allProducts') }}
                {{ scope.row.discount }}{{ $t('coupon.off') }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="recruitStatus"
            label="招募情况"
            align="center"
            width="100"
          >
            <template #default="scope">
              <span v-if="scope.row.recruitStatus === 1">招募中</span>
              <span v-else>停止招募</span>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            align="center"
            :label="$t('crud.menu')"
            width="200"
          >
            <template #default="scope">
              <div
                class="default-btn text-btn"
                @click="onAddOrUpdate(scope.$index)"
              >
                {{ scope.$index+1 > maxLength ? $t('sysManagement.save') : $t('coupon.edit') }}
              </div>
              <div
                v-if="scope.row.recruitStatus === 0"
                class="default-btn text-btn"
                @click="onStopOrStartRecruit(scope.row, 1)"
              >
                {{ $t('user.startRecruit') }}
              </div>
              <el-button
                v-if="scope.row.recruitStatus === 1"
                class="default-btn text-btn"
                @click="onStopOrStartRecruit(scope.row, 0)"
              >
                {{ $t('user.stopRecruit') }}
              </el-button>
              <div
                v-if="scope.$index === dataForm.userLevels.length -1 && scope.$index !== 0"
                class="default-btn text-btn"
                @click="onDeleteRow(scope.$index)"
              >
                {{ $t('user.remove') }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="onGetData"
    />
  </div>
</template>

<script setup>
import AddOrUpdate from './add-or-update.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { isAuth } from '@/utils'

const addOrUpdateVisible = ref(false)
const dataForm = reactive({
  parentId: null,
  id: null,
  levelType: 1,
  userLevels: []
})
const maxLength = ref(0)
const userLevel = [
  {
    id: null,
    level: 0,
    levelName: '',
    levelType: 1,
    needGrowth: 0,
    needAmount: 1,
    recruitStatus: 1,
    term: 1,
    termType: 3,
    img: '',
    discount: 10,
    discountRange: 0,
    discountType: 0,
    presScore: 0,
    rateScore: 1,
    isFreeFee: 0,
    couponList: [],
    userRightsIds: [],
    categorys: null
  }
]
onMounted(() => {
  onGetData()
})

// 获取数据
const onGetData = () => {
  http({
    url: http.adornUrl('/user/userLevel/list'),
    method: 'get',
    params: http.adornParams({
      userLevelType: 1
    })
  }).then(({ data }) => {
    getVipInternationalization(data)
    dataForm.userLevels = data
    maxLength.value = data.length
    // dataForm.userLevels.forEach(item => {
    //   if (item.status === -1) {
    //     isUpdateData = true
    //   }
    // })
  })
}
// const handleChange = (val) => {
//   dataForm.parentId = val[val.length - 1]
// }
// 新增 / 修改
const addOrUpdateRef = ref(null)
const onAddOrUpdate = (index) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(dataForm.userLevels, index)
  })
}
// 删除列
const onDeleteRow = (index) => {
  ElMessageBox.confirm($t('seckill.isDeleOper'), $t('text.tips'), {
    confirmButtonText: $t('coupon.confirm'),
    cancelButtonText: $t('coupon.cancel'),
    type: 'warning'
  }).then(() => {
    // if (dataForm.userLevels.length === 2) {
    //   errorMsg('最后一个会员等级不能删除')
    // }
    dataForm.id = dataForm.userLevels[index].id
    // 删除列并更新数据
    if (dataForm.id) {
      http({
        url: http.adornUrl('/user/userLevel'),
        method: 'delete',
        data: http.adornData(dataForm)
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500
        })
        onGetData()
      }).catch(() => { })
    } else {
      onGetData()
    }
  }).catch(() => { })
}
// 增加列
const onAddRow = () => {
  if (dataForm.userLevels.length >= 50) {
    ElMessage({
      message: $t('user.atMost'),
      type: 'warning'
    })
    return
  }
  if (dataForm.userLevels.length > maxLength.value) {
    ElMessage({
      message: $t('user.saveFirst'),
      type: 'warning'
    })
    return
  }
  let needGrowth = 0
  if (dataForm.userLevels.length > 0 && dataForm.userLevels[maxLength.value - 1].needGrowth !== 0) {
    const currentLastNeedGrowth = dataForm.userLevels[maxLength.value - 1].needGrowth
    needGrowth = dataForm.id = currentLastNeedGrowth < 1000000000 ? currentLastNeedGrowth + 1 : 1000000000
  }
  const level = JSON.parse(JSON.stringify(userLevel[0]))
  level.levelId = null
  level.level = dataForm.userLevels.length + 1
  // if (level.conditionData.commodity) {
  //   level.conditionData.commodity = []
  // }
  const levelNum = parseInt(dataForm.userLevels.length) + 1
  level.levelName = $t('user.vipLevel') + levelNum
  level.levelNameCn = $t('user.vipLevel') + levelNum
  dataForm.userLevels.push(level)
  // console.log(maxLength)
  dataForm.userLevels[maxLength.value].needGrowth = needGrowth
  onAddOrUpdate(dataForm.userLevels.length - 1)
}
// 开始招募 / 停止招募  status: 1开始招募 0停止招募
const onStopOrStartRecruit = (row, status) => {
  const obj = { ...row }
  obj.recruitStatus = status
  const msg = status === 0 ? $t('user.stopRecruitTip') : $t('user.startRecruitTip')
  ElMessageBox.confirm(msg, $t('text.tips'), {
    confirmButtonText: $t('coupon.confirm'),
    cancelButtonText: $t('coupon.cancel'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/user/userLevel/recruitStatus'),
      method: 'put',
      data: http.adornData(obj)
    }).then(() => {
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500
      })
      onGetData()
    }).catch(() => { })
  }).catch(() => { })
}
// const errorMsg = (message) => {
//   ElMessage({
//     message,
//     type: 'error',
//     duration: 1500
//   })
// }

// 国际化
const getVipInternationalization = (data) => {
  if (!data) return
  const lang = localStorage.getItem('bbcLang') || 'zh_CN'
  data.map(element => {
    let levelNameCn, levelNameEn
    if (!element.userLevelLangList) return element
    element.userLevelLangList.map(val => {
      if (val.lang === 0) {
        levelNameCn = val.levelName
      }
      if (val.lang === 1) {
        levelNameEn = val.levelName
      }
      return val
    })
    element.levelName = lang === 'zh_CN' ? levelNameCn : levelNameEn || levelNameCn
    element.levelName = lang === 'zh_CN' ? levelNameCn : levelNameEn || levelNameCn
    return element
  })
}

</script>

<style lang="scss" scoped>
.component-manage-level-vip.distribution-level-set {
  .operation-bar {
    margin-top: 5px;
    &:empty{
      display: none;
    }
  }
}
</style>
